//获取应用实例
const app = getApp();

Page({
	data: {
    hotSearchList:[],
    searchRecord: []
  },
	onLoad: function() {
    this.getHotSearch();
    this.openHistorySearch();
  },

  //获取热搜管理接口
  getHotSearch(){
    var that = this;
    wx.request({
      url: app.globalData.api + '/index.php/wap/HotSearch/getHotSearch',
      method: 'post',
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      data: {
        'p': 1,
        'per':10
      }, 
      success: (res) => {
        console.log(res)
        that.setData({
          hotSearchList: res.data.data
        })
        console.log(that.data.hotSearchList)
      },
    });
  },

  searchSubmit: function (e) {
    console.info('携带数据为：', e.detail.value)
    var that = this
    var inputVal = that.data.recordValue
    var searchRecord = this.data.searchRecord
    if (inputVal == ''||inputVal==undefined) {
      //输入为空时的处理
      console.log("inputVal is null")
    }
    else {
      //将搜索值放入历史记录中,只能放前五条
      if (searchRecord.length < 5) {
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
      else {
        searchRecord.pop()//删掉旧的时间最早的第一条
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
      that.setData({
        searchRecord: searchRecord
      })
      //将历史记录数组整体储存到缓存中
      wx.setStorageSync('searchRecord', searchRecord)
    }
    wx.navigateTo({
      url: '/pages/shop/search-list?name=' + e.detail.value,
    })
  },

  openHistorySearch: function () {
    this.setData({
      searchRecord: wx.getStorageSync('searchRecord') || [],//若无储存则为空
    })
  },

  recordInput:function(e){
    this.setData({
      recordValue:e.detail.value
    })
  },
  search:function(){
    var that = this
    var inputVal = that.data.recordValue
    var searchRecord = this.data.searchRecord
    if (inputVal == '') {
      //输入为空时的处理
    }
    else {
      //将搜索值放入历史记录中,只能放前五条
      if (searchRecord.length < 5) {
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
      else {
        searchRecord.pop()//删掉旧的时间最早的第一条
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
      that.setData({
        searchRecord: searchRecord
      })
      //将历史记录数组整体储存到缓存中
      wx.setStorageSync('searchRecord', searchRecord)
    }
   

  },



  //清除历史记录
  historyDelFn: function () {
    wx.clearStorageSync('searhRecord')
    this.setData({
      searchRecord: []
    })
  },
});
